package cn.yl.gateway.filter;

import cn.yl.api.server.result.Result;
import cn.yl.api.server.util.JwtUtil;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局网关
 */
@Component
public class GatewayFilter implements GlobalFilter {


    private final JwtUtil jwtUtil;
    private static List<String> whiteList = new ArrayList<>();
    private static List<String> blackList = new ArrayList<>();

    private static final String MESSAGE = "用户信息获取失败(jwt)";

    static {
        whiteList.add("login");
        whiteList.add("getAllCourse");
        whiteList.add("getAdsBySpaceId");
        whiteList.add("getCourseCommentList");
        whiteList.add("checkWxStatus");
        whiteList.add("playerUrl");
        whiteList.add("wxpay/notify");
//        blackList.add("getOKOrderCourseIds");
    }

    public GatewayFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        boolean flag = false;
        for (String white: whiteList) {
            if (path.contains(white)) {
                // 白名单，不需要验证token（jwt）
                flag = true;
                break;
            }
        }
//        for (String s : blackList) {
//            if (path.contains(s)) {
//                // 白名单，不需要验证token（jwt）
//                flag = true;
//                break;
//            }
//        }
        if (!flag) {
            try {
                HttpHeaders headers = request.getHeaders();
                List<String> jwtList = headers.get("jwt");
                String jwt = jwtList.get(0);
                Claims claims = jwtUtil.parseJWT(jwt);
            } catch (Exception e) {
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                Result error = Result.error();
                error.setMessage(MESSAGE);
                DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONString(error).getBytes(StandardCharsets.UTF_8));
                return response.writeWith(Mono.just(wrap));
            }
            // 3.获取头信息中的token
            // 4.jwt.paseJwt(token)  正常是是没有问题， 解析的时候会抛出异常
            //  4.1 返回json字符串 {"code", 302}

            // 设置返回类型为json
            // 返回
        }
        // 1.白名单 list login,getCourseAll....
        // 2.uri

//        PathContainer pathContainer = request.getPath().pathWithinApplication();
//        // 添加gatewayKey，防止下游接口直接被访问
//        ServerHttpRequest.Builder mutate = request.mutate();
//        mutate.header("gatewayKey", "key");
//        chain.filter(exchange.mutate().request(mutate.build()).build());
        return chain.filter(exchange);
    }
}